package com.zrrd.mcl.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zrrd.mcl.model.enums.PaymentType;
import com.zrrd.mcl.model.order.OrderInfo;
import com.zrrd.mcl.order.client.OrderFeignClient;
import com.zrrd.mcl.payment.config.AlipayConfig;
import com.zrrd.mcl.payment.service.AlipayService;
import com.zrrd.mcl.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String createPayCode(Long orderId) throws AlipayApiException {
        //获取订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //保存交易记录
        paymentInfoService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        //创建请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置同步回调
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
        //创建一个参数集合
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", orderInfo.getOutTradeNo());
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("total_amount", orderInfo.getTotalAmount());
        map.put("subject", orderInfo.getTradeBody());
        //生成二维码
        alipayRequest.setBizContent(JSON.toJSONString(map));
        //调用支付版SDK生成表单（发请求）
        String body = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("请求支付结果=====>" + body);
        //返回结果
        return body;
    }
}
